<template>
  <div class="deposit">
    <div class="page-header">
      <h2 class="page-title">充值</h2>
      <p class="page-subtitle">向您的钱包地址充值 USDT</p>
    </div>
    
    <el-card class="deposit-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <el-icon class="header-icon"><Plus /></el-icon>
          <span>充值 USDT</span>
        </div>
      </template>
      
      <el-steps :active="currentStep" finish-status="success" style="margin-bottom: 40px">
        <el-step title="选择充值方式" />
        <el-step title="生成充值地址" />
        <el-step title="等待确认" />
      </el-steps>
      
      <div v-if="currentStep === 0" class="step-content">
        <el-alert
          title="充值说明"
          type="info"
          :closable="false"
          style="margin-bottom: 20px"
        >
          <p>1. 选择充值币种（目前支持 USDT）</p>
          <p>2. 系统将为您生成唯一的充值地址</p>
          <p>3. 向该地址转账后，系统将自动确认并到账</p>
        </el-alert>
        
        <el-form :model="depositForm" label-width="120px">
          <el-form-item label="充值币种">
            <el-select v-model="depositForm.currency" style="width: 100%">
              <el-option label="USDT" value="USDT" />
            </el-select>
          </el-form-item>
          <el-form-item label="选择网络">
            <el-radio-group v-model="depositForm.chain">
              <el-radio label="ETH">
                <span>以太坊 (ERC20)</span>
                <el-tag type="info" size="small" style="margin-left: 8px">推荐</el-tag>
              </el-radio>
              <el-radio label="BSC">
                <span>币安智能链 (BEP20)</span>
                <el-tag type="success" size="small" style="margin-left: 8px">手续费更低</el-tag>
              </el-radio>
            </el-radio-group>
            <div style="margin-top: 8px; font-size: 12px; color: #909399;">
              <p v-if="depositForm.chain === 'ETH'">• 使用以太坊网络，手续费较高但更稳定</p>
              <p v-if="depositForm.chain === 'BSC'">• 使用币安智能链，手续费更低，到账更快</p>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="generateAddress">
              生成充值地址
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <div v-if="currentStep === 1" class="step-content">
        <el-alert
          title="重要提示"
          type="warning"
          :closable="false"
          style="margin-bottom: 20px"
        >
          <p v-if="selectedChain === 'ETH'">请确保使用正确的网络类型（ERC20/Ethereum）进行充值</p>
          <p v-if="selectedChain === 'BSC'">请确保使用正确的网络类型（BEP20/BSC/币安智能链）进行充值</p>
          <p>使用错误的网络可能导致资产丢失且无法找回</p>
        </el-alert>
        
        <div class="address-info">
          <el-form-item label="充值地址">
            <el-input
              v-model="depositAddress"
              readonly
              style="width: 100%"
            >
              <template #append>
                <el-button @click="copyAddress">复制</el-button>
              </template>
            </el-input>
          </el-form-item>
          
          <div class="qr-code">
            <img :src="qrCodeUrl" alt="QR Code" v-if="qrCodeUrl" />
          </div>
          
          <!-- 币安充值教程 -->
          <el-card class="tutorial-card" shadow="never">
            <template #header>
              <div class="tutorial-header">
                <el-icon><Guide /></el-icon>
                <span>币安充值教程</span>
              </div>
            </template>
            <el-steps direction="vertical" :active="0" finish-status="success">
              <el-step>
                <template #title>
                  <span class="step-title">登录币安账户</span>
                </template>
                <template #description>
                  <div class="step-description">
                    访问 <el-link href="https://www.binance.com" target="_blank" type="primary">www.binance.com</el-link> 并登录您的币安账户
                  </div>
                </template>
              </el-step>
              <el-step>
                <template #title>
                  <span class="step-title">进入钱包页面</span>
                </template>
                <template #description>
                  <div class="step-description">
                    点击右上角"钱包" → 选择"现货钱包"或"资金" → 点击"充值"
                  </div>
                </template>
              </el-step>
              <el-step>
                <template #title>
                  <span class="step-title">选择币种和网络</span>
                </template>
                <template #description>
                  <div class="step-description">
                    <p>1. 在搜索框输入"USDT"</p>
                    <p v-if="selectedChain === 'ETH'">
                      2. <strong class="highlight">重要：选择网络类型为 "ERC20" 或 "Ethereum (ETH)"</strong>
                    </p>
                    <p v-if="selectedChain === 'BSC'">
                      2. <strong class="highlight">重要：选择网络类型为 "BEP20" 或 "BSC" 或 "币安智能链"</strong>
                    </p>
                    <p v-if="selectedChain === 'ETH'">3. 不要选择 BEP20 (BSC)、TRC20 (TRON) 等其他网络</p>
                    <p v-if="selectedChain === 'BSC'">3. 不要选择 ERC20 (ETH)、TRC20 (TRON) 等其他网络</p>
                  </div>
                </template>
              </el-step>
              <el-step>
                <template #title>
                  <span class="step-title">复制充值地址</span>
                </template>
                <template #description>
                  <div class="step-description">
                    <p>1. 点击上方"复制"按钮复制您的充值地址</p>
                    <p>2. 将地址粘贴到币安的充值地址输入框</p>
                    <p>3. 或者扫描上方的二维码</p>
                  </div>
                </template>
              </el-step>
              <el-step>
                <template #title>
                  <span class="step-title">确认并提交</span>
                </template>
                <template #description>
                  <div class="step-description">
                    <p>1. 在币安输入充值金额</p>
                    <p v-if="selectedChain === 'ETH'">2. 仔细核对地址和网络类型（ERC20）</p>
                    <p v-if="selectedChain === 'BSC'">2. 仔细核对地址和网络类型（BEP20/BSC）</p>
                    <p>3. 完成安全验证（邮箱/短信/2FA）</p>
                    <p>4. 确认提交转账</p>
                  </div>
                </template>
              </el-step>
              <el-step>
                <template #title>
                  <span class="step-title">等待到账</span>
                </template>
                <template #description>
                  <div class="step-description">
                    <p>1. 转账通常需要 5-30 分钟到账（取决于网络拥堵情况）</p>
                    <p>2. 系统会自动检测并确认您的充值</p>
                    <p>3. 到账后可在"交易记录"中查看</p>
                    <p>4. 点击下方按钮确认您已完成转账</p>
                  </div>
                </template>
              </el-step>
            </el-steps>
          </el-card>
          
          <el-button type="primary" @click="confirmDeposit" style="width: 100%; margin-top: 20px;" size="large">
            我已转账，等待确认
          </el-button>
          
          <!-- 余额查询和检查区域 -->
          <el-card class="balance-card" shadow="never" style="margin-top: 30px;">
            <template #header>
              <div class="balance-header">
                <el-icon><Wallet /></el-icon>
                <span>余额查询</span>
              </div>
            </template>
            <div class="balance-content">
              <el-space direction="vertical" style="width: 100%" size="large">
                <div class="balance-info">
                  <div class="balance-item">
                    <span class="label">链上余额：</span>
                    <span class="value" :class="{ 'synced': balanceInfo.synced }">
                      {{ formatBalanceWithUnit(balanceInfo.chainBalance, 'USDT', usdtDecimals) }}
                    </span>
                  </div>
                  <div class="balance-item">
                    <span class="label">数据库余额：</span>
                    <span class="value">{{ formatBalanceWithUnit(balanceInfo.dbBalance, 'USDT', usdtDecimals) }}</span>
                  </div>
                  <div v-if="balanceInfo.synced !== null" class="balance-item">
                    <el-tag :type="balanceInfo.synced ? 'success' : 'warning'" size="small">
                      {{ balanceInfo.synced ? '已同步' : '未同步' }}
                    </el-tag>
                  </div>
                </div>
                <el-space>
                  <el-button type="primary" @click="checkChainBalance" :loading="checkingBalance">
                    <el-icon><Refresh /></el-icon>
                    查询链上余额
                  </el-button>
                  <el-button type="warning" @click="manualCheckDeposit" :loading="checkingDeposit">
                    <el-icon><Search /></el-icon>
                    手动检查充值
                  </el-button>
                </el-space>
                <el-alert
                  v-if="balanceInfo.message"
                  :title="balanceInfo.message"
                  :type="balanceInfo.messageType || 'info'"
                  :closable="false"
                  show-icon
                />
              </el-space>
            </div>
          </el-card>
        </div>
      </div>
      
      <div v-if="currentStep === 2" class="step-content">
        <el-result
          icon="success"
          title="充值地址已生成"
          sub-title="请向上述地址转账，系统将自动确认并到账"
        >
          <template #extra>
            <el-button type="primary" @click="resetDeposit">重新充值</el-button>
            <el-button @click="$router.push('/transactions')">查看交易记录</el-button>
          </template>
        </el-result>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Guide, Wallet, Refresh, Search } from '@element-plus/icons-vue'
import QRCode from 'qrcode'
import { walletApi } from '../api/wallet'
import { formatBalanceWithUnit } from '../utils/format'

const currentStep = ref(0)
const depositForm = reactive({
  currency: 'USDT',
  chain: 'ETH' // 默认使用 ETH，可选 ETH 或 BSC
})
const depositAddress = ref('')
const qrCodeUrl = ref('')
const selectedChain = ref('ETH') // 用于显示当前选择的链
const checkingBalance = ref(false)
const checkingDeposit = ref(false)
const usdtDecimals = ref(6) // 默认6位，从后端获取
const balanceInfo = reactive({
  chainBalance: null as number | null,
  dbBalance: null as number | null,
  synced: null as boolean | null,
  message: '',
  messageType: 'info' as 'success' | 'warning' | 'error' | 'info'
})

const generateAddress = async () => {
  try {
    const result: any = await walletApi.generateDepositAddress(depositForm.currency, depositForm.chain)
    depositAddress.value = result.address || result.data?.address || ''
    
    if (!depositAddress.value) {
      throw new Error('地址生成失败')
    }
    
    // 保存当前选择的链，用于显示提示信息
    selectedChain.value = depositForm.chain
    
    // 生成二维码
    qrCodeUrl.value = await QRCode.toDataURL(depositAddress.value, {
      width: 300,
      margin: 2
    })
    
    currentStep.value = 1
    ElMessage.success('充值地址已生成')
  } catch (error: any) {
    ElMessage.error(error.message || '生成地址失败')
  }
}

const copyAddress = () => {
  if (!depositAddress.value) {
    ElMessage.warning('地址未生成')
    return
  }
  
  navigator.clipboard.writeText(depositAddress.value).then(() => {
    ElMessage.success('地址已复制')
  }).catch(() => {
    ElMessage.error('复制失败')
  })
}

const confirmDeposit = async () => {
  try {
    // 手动触发一次充值检查
    await walletApi.checkDeposit(depositForm.currency, selectedChain.value)
    currentStep.value = 2
    ElMessage.info('请等待区块确认，系统将自动到账')
    // 自动查询一次余额
    setTimeout(() => {
      checkChainBalance()
    }, 2000)
  } catch (error: any) {
    console.error('检查充值失败:', error)
    currentStep.value = 2
    ElMessage.info('请等待区块确认，系统将自动到账')
  }
}

// 查询链上余额
const checkChainBalance = async () => {
  if (!depositAddress.value) {
    ElMessage.warning('请先生成充值地址')
    return
  }
  
  checkingBalance.value = true
  balanceInfo.message = ''
  
  try {
    const result: any = await walletApi.getChainBalance(depositForm.currency, selectedChain.value)
    
    // 响应拦截器已经返回了 data.data，所以 result 直接就是数据对象
    // 后端已经统一转换了余额，直接使用即可
    if (result && (result.chainBalance !== undefined || result.dbBalance !== undefined)) {
      // 更新 usdtDecimals（如果后端返回了）
      if (result.usdtDecimals !== undefined) {
        usdtDecimals.value = result.usdtDecimals
      }
      
      balanceInfo.chainBalance = result.chainBalance || 0
      balanceInfo.dbBalance = result.dbBalance || 0
      balanceInfo.synced = result.synced || false
      
      if (result.synced) {
        balanceInfo.message = '余额已同步'
        balanceInfo.messageType = 'success'
      } else {
        balanceInfo.message = `余额不一致！链上: ${formatBalanceWithUnit(result.chainBalance, 'USDT', usdtDecimals.value)}, 数据库: ${formatBalanceWithUnit(result.dbBalance, 'USDT', usdtDecimals.value)}`
        balanceInfo.messageType = 'warning'
      }
      
      ElMessage.success('查询成功')
    } else {
      throw new Error('查询失败：返回数据格式错误')
    }
  } catch (error: any) {
    console.error('查询链上余额失败:', error)
    balanceInfo.message = '查询失败: ' + (error.message || '未知错误')
    balanceInfo.messageType = 'error'
    ElMessage.error(error.message || '查询链上余额失败')
  } finally {
    checkingBalance.value = false
  }
}

// 手动检查充值
const manualCheckDeposit = async () => {
  if (!depositAddress.value) {
    ElMessage.warning('请先生成充值地址')
    return
  }
  
  checkingDeposit.value = true
  balanceInfo.message = ''
  
  try {
    const result: any = await walletApi.checkDeposit(depositForm.currency, selectedChain.value)
    
    // 响应拦截器已经返回了 data.data，所以 result 直接就是数据对象
    // 后端已经统一转换了余额，直接使用即可
    if (result) {
      // 更新 usdtDecimals（如果后端返回了）
      if (result.usdtDecimals !== undefined) {
        usdtDecimals.value = result.usdtDecimals
      }
      
      balanceInfo.dbBalance = result.dbBalance || 0
      balanceInfo.chainBalance = result.chainBalance || 0
      balanceInfo.synced = result.synced || false
      
      const txCount = result.transactionCount || 0
      const totalDeposit = result.totalDeposit || 0
      
      if (txCount > 0) {
        balanceInfo.message = `检查完成！找到 ${txCount} 笔充值记录，总充值金额: ${formatBalanceWithUnit(totalDeposit, 'USDT', usdtDecimals.value)}`
        balanceInfo.messageType = 'success'
        ElMessage.success(`检查完成，找到 ${txCount} 笔充值记录，总金额: ${formatBalanceWithUnit(totalDeposit, 'USDT', usdtDecimals.value)}`)
      } else {
        const networkType = selectedChain.value === 'ETH' ? 'ERC20' : 'BEP20/BSC'
        balanceInfo.message = `检查完成，但未找到充值记录。请确认：1) 是否已转账 2) 是否使用了正确的网络(${networkType}) 3) 是否转账到正确的地址`
        balanceInfo.messageType = 'warning'
        ElMessage.warning('未找到充值记录，请确认是否已转账')
      }
      
      // 如果链上余额大于0但数据库余额为0，说明有充值但未记录
      if (result.chainBalance > 0 && result.dbBalance === 0) {
        balanceInfo.message = `⚠️ 发现链上有余额 ${formatBalanceWithUnit(result.chainBalance, 'USDT', usdtDecimals.value)}，但数据库未记录！请检查后端日志。`
        balanceInfo.messageType = 'error'
        ElMessage.error('链上有余额但数据库未记录，请查看后端日志')
      }
    } else {
      throw new Error('检查失败：返回数据格式错误')
    }
  } catch (error: any) {
    console.error('检查充值失败:', error)
    balanceInfo.message = '检查失败: ' + (error.message || '未知错误')
    balanceInfo.messageType = 'error'
    ElMessage.error(error.message || '检查充值失败')
  } finally {
    checkingDeposit.value = false
  }
}

const resetDeposit = () => {
  currentStep.value = 0
  depositAddress.value = ''
  qrCodeUrl.value = ''
  selectedChain.value = depositForm.chain
}
</script>

<style scoped>
.deposit {
  padding: 0;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-subtitle {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.deposit-card {
  margin-bottom: 0;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-icon {
  font-size: 18px;
  color: #409eff;
}

.step-content {
  min-height: 300px;
  padding: 20px 0;
}

.address-info {
  text-align: center;
}

.qr-code {
  margin: 30px 0;
  display: inline-block;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.qr-code img {
  width: 300px;
  height: 300px;
  display: block;
}

.tutorial-card {
  margin-top: 30px;
  border: 1px solid #e4e7ed;
}

.tutorial-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
}

.tutorial-header .el-icon {
  color: #409eff;
  font-size: 18px;
}

.step-title {
  font-weight: 500;
  color: #303133;
}

.step-description {
  margin-top: 8px;
  color: #606266;
  line-height: 1.8;
  font-size: 14px;
}

.step-description p {
  margin: 4px 0;
}

.highlight {
  color: #e6a23c;
  font-weight: 600;
  background: #fdf6ec;
  padding: 2px 6px;
  border-radius: 3px;
}

.balance-card {
  border: 1px solid #e4e7ed;
  background: #fafafa;
}

.balance-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
}

.balance-header .el-icon {
  color: #409eff;
  font-size: 18px;
}

.balance-content {
  padding: 10px 0;
}

.balance-info {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.balance-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.balance-item .label {
  font-weight: 500;
  color: #606266;
  min-width: 100px;
}

.balance-item .value {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.balance-item .value.synced {
  color: #67c23a;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .qr-code img {
    width: 250px;
    height: 250px;
  }
}
</style>

